﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Wicresoft.EVM.Reporting
{
    static class WebUtil
    {
        /// <summary>
        /// Send a raw http request then return http status code 
        ///     and response body if status code equals to 200 
        /// </summary>
        public static HttpStatusCode Request(string url, out string body, string method = "POST", CookieContainer cookies = null, NameValueCollection headers = null, NameValueCollection data = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("url");

            if (method.ToUpper() != "POST")
                throw new NotSupportedException(method + " is not supported yet. Currently, only HTTP POST is fine.");

            if (data != null)
                throw new NotSupportedException("HTTP payload is not supported yet.");

            body = null;

            var wr = WebRequest.Create(url) as HttpWebRequest;
            wr.AllowAutoRedirect = false;
            wr.Method = method;

            // header
            if (headers != null)
                wr.Headers.Add(headers);

            // cookie
            if (cookies != null)
                wr.CookieContainer = cookies;

            // get response
            HttpWebResponse ws;

            try
            {
                ws = wr.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                ws = e.Response as HttpWebResponse;
            }

            if (ws == null)
                return HttpStatusCode.InternalServerError;
            else
            {
                HttpStatusCode code = ws.StatusCode;

                if (code == HttpStatusCode.OK)
                {
                    body = GetResponseBody(ws);
                }

                return code;
            }
        }

        private static string GetResponseBody(HttpWebResponse response)
        {
            Encoding encoding;

            try
            {
                encoding = Encoding.GetEncoding(response.CharacterSet);
            }
            catch (ArgumentException)
            {
                encoding = Encoding.Default;
            }

            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[4096];

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to text
                    tempString = encoding.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            return sb.ToString();
        }
    }
}